#!/usr/bin/env python
# coding=utf-8
"""WTFM"""
import argparse
import sys
import datetime
from subprocess import Popen, PIPE, STDOUT

PUBLISH_PATH = "/DMP/tenant/%(tenant_id)d/publish/%(org_id)d/%(date)s*"
GET_INPUT_CMD = "hdfs dfs -ls %(path)s |grep _SUCCESS | awk '{print $8}'"
TAG_DS_PATH = "/DMP/tenant/%(tenant_id)d/src-data/tag/%(ds_id)d/raw/%(date)s"
HDFS_CP_CMD = "hdfs dfs -mkdir -p %(out_path)s && hdfs dfs -cp %(input_path)s/* %(out_path)s"


def main():
    arg_parser = argparse.ArgumentParser(
        description="用于在Saas DMP v3中, 将一个租户的标签给到另一个租户作为标签数据源")

    arg_parser.add_argument("from_tenant", type=int, default=1, help="来源租户id")
    arg_parser.add_argument("from_org", type=int, default=41,
                            help="来源租户的机构id, 将此租户此机构publish的标签, cp到目标租户")
    arg_parser.add_argument("to_tenant", type=int, default=4, help="目标租户id")
    arg_parser.add_argument("to_ds", type=int, default=1, help="目标租户的目标数据源id")
    arg_parser.add_argument("-d", "--date", dest="date")

    args = arg_parser.parse_args()

    yesterday = datetime.date.today() - datetime.timedelta(days=1)
    date = args.date if args.date else yesterday.strftime("%Y%m%d")

    from_path = get_input(args.from_tenant, args.from_org, date)
    print("Find input path %s" % from_path)
    cp_to_out(from_path, args.to_tenant, args.to_ds, date)


def get_input(tenant_id, org_id, date):
    publish_path = PUBLISH_PATH % {
        "tenant_id": tenant_id, "org_id": org_id, "date": date}
    cmd = GET_INPUT_CMD % {"path": publish_path}
    process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
    out = process.communicate()[0]
    rcode = process.returncode
    if rcode == 0:
        path = out.decode("utf-8").strip('\n')
        if path.rfind('/') != -1:
            return path[0: path.rfind('/')]
        else:
            print("input path %s no /" % path)
            sys.exit(1)
    else:
        print("Cant Find input path")
        sys.exit(1)


def cp_to_out(from_path, tenant_id, ds_id, date):
    out_path = TAG_DS_PATH % {
        "tenant_id": tenant_id, "ds_id": ds_id, "date": date}
    cmd = HDFS_CP_CMD % {"input_path": from_path, "out_path": out_path}
    print(cmd)
    process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
    out = process.communicate()[0]
    rcode = process.returncode
    if rcode == 0:
        print(out)
    else:
        print("Error while cp")
        sys.exit(1)


if __name__ == '__main__':
    main()
